package ie.live.byrnep.pleasesleephere.bookroom;

import ie.live.byrnep.pleasesleephere.R;

import ie.live.byrnep.pleasesleephere.base.CloudConnection;
import ie.live.byrnep.pleasesleephere.base.MyViewBinder;
import java.util.HashMap;
import java.util.List;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private String listUrls;
	private EditText searchtext;
	private String entityKey=null;
	private CloudConnection cloudConnection ;
	private List<HashMap<String, Object>> aList;
	private View listImgView;
	private String[] from = { "title", "des", "price","photo"};
	// Ids of views in listview_layout
	private int[] to = { R.id.title, R.id.description, R.id.price, R.id.thumbImg};
	private int distanceChoice=-1;
	private boolean currentDistanceChoice=false;
	LocationListener locationListener=null;
	LocationManager locationMangaer = null;
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		//cloudConnection = new CloudConnection(this);
		searchtext = (EditText) findViewById(R.id.searchText);
		searchtext.setText("carlow");
		listImgView = (View) findViewById(R.id.thumbImg);
		final Button SearchButton = (Button) findViewById(R.id.button1);
		SearchButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View v) {

				new RetrieveRooms().execute(searchtext.getText().toString());
				//checkLocation(searchtext.getText().toString());
			}
		});
		final Button GPSButton = (Button) findViewById(R.id.gpsButton);
		//GPSButton.setOnClickListener(new GpsButtonEvent());
		GPSButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View v) {
				String lat = "52.789995", lon ="-6.875896";
				/*String urlKeyString;		
				cloudConnection = new CloudConnection(MainActivity.this);		
				urlKeyString = cloudConnection.checkLocationFromGps(lon,lat);
				if (urlKeyString != null) {
					aList = cloudConnection.retrieveListItems(urlKeyString); 
					cloudConnection = null;
					populateList(aList, from, to);
				} */
				
				
				
				
				
				
				
				
				
				
				
				DisplayDialog();
				//wait for maximum distance to be selected

				/*LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
				boolean enabled = service
				  .isProviderEnabled(LocationManager.GPS_PROVIDER);
			
				// Check if enabled and if not send user to the GSP settings
				// Better solution would be to display a dialog and suggesting to 
				// go to the settings
				if (!enabled) {
				  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				  startActivity(intent);
				}
				else{
					locationMangaer = (LocationManager)   
							  getSystemService(Context.LOCATION_SERVICE);  
					
					
					locationListener = new MyLocationListener();  
					  
					   locationMangaer.requestLocationUpdates(LocationManager  
					   .GPS_PROVIDER, 3000, 5,locationListener);  
					   locationMangaer.requestLocationUpdates(LocationManager  
							   .NETWORK_PROVIDER, 3000, 5,locationListener);
					   
					   //locationMangaer.removeUpdates(locationListener);
				}*/
			}
		});
		
	}
	
	private void DisplayDialog()
    {	
	   	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	   	builder.setTitle("Select Distance")
        .setItems(R.array.distance, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	distanceChoice = which;
            	currentDistanceChoice=true;
            	Toast.makeText(getBaseContext(),
						"The return value was: " + distanceChoice,  
						Toast.LENGTH_LONG).show(); 
            	LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
				boolean enabled = service
				  .isProviderEnabled(LocationManager.GPS_PROVIDER);
			
				// Check if enabled and if not send user to the GSP settings
				// Better solution would be to display a dialog and suggesting to 
				// go to the settings
				if (!enabled) {
				  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				  startActivity(intent);
				}
				else{
					locationMangaer = (LocationManager)   
							  getSystemService(Context.LOCATION_SERVICE);  
					
					
					locationListener = new MyLocationListener();  
					  
					   locationMangaer.requestLocationUpdates(LocationManager  
					   .GPS_PROVIDER, 3000, 5,locationListener);  
					   locationMangaer.requestLocationUpdates(LocationManager  
							   .NETWORK_PROVIDER, 3000, 5,locationListener);
					   
					   //locationMangaer.removeUpdates(locationListener);
				}
        }
        });
	  	 AlertDialog alert = builder.create();
	  	 alert.show();
    }
	


	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private void populateList(final List<HashMap<String, Object>> aList2,
			String[] from, int[] to) {
		
		SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList2,	  R.layout.listview_layout, from, to);
		adapter.setViewBinder(new MyViewBinder());
		
		// Getting a reference to listview of main.xml layout file
		ListView listView = (ListView) findViewById(R.id.listview);
		// Setting the adapter to the listView
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {

				// I modified HERE
				String title = ((TextView) view.findViewById(R.id.title))
						.getText().toString();
				/*
				 * change to while loop
				 * it is checking all elements of list
				 * needs to jump out when it finds
				 */
				
				//initialise entityKey to null to allow user select a different list item
				entityKey = null;
				for (HashMap<String, Object> item : aList2) {
					if (entityKey ==null && item.get("title")== title) {
						entityKey = item.get("key").toString();
					}
				}
				
				// Starting new intent
				Intent in = new Intent(getApplicationContext(), Room.class);
				in.putExtra("entity_key", entityKey);
				startActivityForResult(in, position);
			}
		});

	}
	private class MyLocationListener implements LocationListener {  
        @Override  
        public void onLocationChanged(Location loc) { 
        	//dd;
        	/*String lat = "52.789995", lon ="-6.875896";
        	String cordArray[] = {lon,lat};*/
        	String cordArray[] = {"" + loc.getLongitude(), "" + loc.getLatitude()};
        	
        	
            Toast.makeText(getBaseContext(),"Location changed : Lat: " +  
            								loc.getLatitude()+ " Lng: " + loc.getLongitude(),  
            								Toast.LENGTH_SHORT).show();  
            								String longitude = "Longitude: " +loc.getLongitude();    
            								String latitude = "Latitude: " +loc.getLatitude();  
           locationMangaer.removeUpdates(locationListener);								
           new RetrieveRoomsFromGps().execute(cordArray);
        }  
  
        @Override  
        public void onProviderDisabled(String provider) {}  
  
        @Override  
        public void onProviderEnabled(String provider) {}  
  
        @Override  
        public void onStatusChanged(String provider,int status, Bundle extras) {}  
    } 
	
	
	class RetrieveRooms extends AsyncTask<String, Void, List<HashMap<String, Object>>> {
		ProgressDialog dialog;
		protected void onPreExecute(){
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.setTitle(DOWNLOAD_SERVICE);
			dialog.show();
		}
		@Override
		protected List<HashMap<String, Object>> doInBackground(String... params) {
			String urlKeyString;		
			cloudConnection = new CloudConnection(MainActivity.this);		
			urlKeyString = cloudConnection.checkForLocation(params[0].toString());
			if (urlKeyString != null) {
				aList = cloudConnection.retrieveListItems(urlKeyString); 
				cloudConnection = null;
			} 
			else {
				// TODO
				// no entry found in cloud for search criteria
				// display message to user
			}
			dialog.dismiss();
			return aList;
		}
		protected void onProgressUpdate(int ... progress){}	
		@Override
		
	    protected void onPostExecute(List<HashMap<String, Object>> aList) {
			populateList(aList, from, to);
		}
	}
	
	
	
	class RetrieveRoomsFromGps extends AsyncTask<String, Void, List<HashMap<String, Object>>> {
		ProgressDialog dialog;
		protected void onPreExecute(){
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.setTitle(DOWNLOAD_SERVICE);
			dialog.show();
		}
		@Override
		protected List<HashMap<String, Object>> doInBackground(String... params) {
			String urlKeyString;		
			cloudConnection = new CloudConnection(MainActivity.this);	
			urlKeyString = cloudConnection.checkLocationFromGps(params[0].toString(),params[1].toString(),distanceChoice);
			//reset distanceChoice value
			currentDistanceChoice = false;
			if (urlKeyString != null) {
				aList = cloudConnection.retrieveListItems(urlKeyString); 
				cloudConnection = null;
			} 
			else {
				// TODO
				// no entry found in cloud for search criteria
				// display message to user
			}
			dialog.dismiss();
			return aList;
		}
		protected void onProgressUpdate(int ... progress){}	
		@Override
		
	    protected void onPostExecute(List<HashMap<String, Object>> aList) {
			populateList(aList, from, to);
		}
	}
	
}
